package com.zzw.data;

public class MyReadWriteLock {

	private int readThreadCounter = 0;
    private int waitingWriteCounter = 0;
    private int writeThreadCounter = 0;
    private boolean writeFlag = true;

    public synchronized void readLock() throws InterruptedException {
        while (writeThreadCounter > 0 || (writeFlag && waitingWriteCounter > 0)) {
            wait();
        }
        readThreadCounter++;
    }


    public synchronized void readUnlock() {
        readThreadCounter--;
        writeFlag = true;
        notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        waitingWriteCounter++;
        try {
            while (readThreadCounter > 0 || writeThreadCounter > 0) {
                wait();
            }
        } finally {
            waitingWriteCounter--;
        }
        writeThreadCounter++;
    }

    public synchronized void writeUnlock() {
        writeThreadCounter--;
        writeFlag = false;
        notifyAll();
    }
}
